package com.cube.backribs.activity;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.cube.backribs.R;
import com.cube.backribs.common.CommonConst;
import com.cube.backribs.common.CommonValues;
import com.cube.backribs.common.HomeWebChromeClient;
import com.cube.backribs.common.HomeWebViewClient;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class HomeWebViewActivity extends Activity implements OnClickListener {

    private static final String TAG = "HomeWebViewActivity";

    private WebView mWebView;
    private HomeWebChromeClient mWebChromeClient;
    private WebSettings mWebSettings;
    private Animation mFadeInAnimation;
    private Animation mFadeOutAnimation;
    private RelativeLayout mTitleLayout;
    private Button mLoginButton;

    private String mURL;
    private long mBackKeyPressedTime = 0;

    public ProgressBar mProgressBarView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        initWebView();
        initWebViewSetting();
        initAnimation();
        loadWebView();
    }

    @Override
    protected void onResume() {
        super.onResume();

        callHiddenWebViewMethod("onResume");
        mWebView.resumeTimers();
    }

    @Override
    public void onBackPressed() {
        if (mWebChromeClient.mCustomView != null) {
            mWebView.reload();
            Log.i(TAG, "Reload the web view");
        } else if (mWebView.canGoBack()) {
            mWebView.goBack();
            Log.i(TAG, "Back to the previous page");
        } else {
            if (System.currentTimeMillis() > mBackKeyPressedTime + 2000) {
                mBackKeyPressedTime = System.currentTimeMillis();
                Toast.makeText(this, getString(R.string.toast_back_pressed),
                        Toast.LENGTH_SHORT).show();
                return;
            } else {
                finish();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mWebView.clearHistory();
        mWebView.clearFormData();
        mWebView.clearCache(true);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CommonConst.REQUEST_CODE_LOGIN:
                if (resultCode == RESULT_OK) {

                }
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.home_title_login:
                prepareLogin();
                break;
            default:
                break;
        }
    }

    private void initWebView() {
        setContentView(R.layout.home_web_view);

        // Support login from web.
        mTitleLayout = (RelativeLayout) findViewById(R.id.title_layout);
        mTitleLayout.setVisibility(View.GONE);
        
        mLoginButton = (Button) findViewById(R.id.home_title_login);
        mLoginButton.setOnClickListener(this);
        updateLoginButton();

        // Initialize web view
        mWebView = (WebView) findViewById(R.id.web_view);

        mWebChromeClient = new HomeWebChromeClient(HomeWebViewActivity.this);
        mWebView.setWebViewClient(new HomeWebViewClient(
                HomeWebViewActivity.this));
        mWebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        mWebView.setWebChromeClient(mWebChromeClient);
    }

    private void initWebViewSetting() {
        mWebSettings = mWebView.getSettings();
        mWebSettings.setJavaScriptEnabled(true);
        mWebSettings.setDomStorageEnabled(true);
        webViewZoomSetting(true);
        mWebSettings.setPluginState(PluginState.ON_DEMAND);
        mWebSettings.setLoadWithOverviewMode(true);
        mWebSettings.setUseWideViewPort(true);

        mProgressBarView = (ProgressBar) findViewById(R.id.web_view_progress_bar);
    }

    private void initAnimation() {
        mFadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in);
        mFadeOutAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_out);
    }

    private void callHiddenWebViewMethod(String name) {
        if (mWebView != null) {
            try {
                Method method = WebView.class.getMethod(name);
                method.invoke(mWebView);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        }
    }

    private void webViewZoomSetting(boolean zoomSet) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            mWebSettings.setDisplayZoomControls(false);
        }

        mWebSettings.setSupportZoom(zoomSet);
        mWebSettings.setBuiltInZoomControls(zoomSet);
        mWebSettings.setUseWideViewPort(zoomSet);
    }

    private void loadWebView() {
        mURL = CommonValues.HOME_URL;
        mWebView.loadUrl(mURL);
    }

    public WebView getWebView() {
        return mWebView;
    }

    public void webViewLoadStart() {
        mProgressBarView.startAnimation(mFadeInAnimation);
        mProgressBarView.setVisibility(ProgressBar.VISIBLE);
    }

    public void webViewLoadFinish() {
        mProgressBarView.startAnimation(mFadeOutAnimation);
        mProgressBarView.setVisibility(ProgressBar.GONE);
    }

    public void prepareLogin() {
        SharedPreferences prefs = getSharedPreferences(
                CommonValues.PREFS_LOGIN, MODE_PRIVATE);
        String loginId = prefs.getString(CommonValues.PREFS_KEY_ID, null);
        String loginPassword = prefs.getString(CommonValues.PREFS_KEY_PASSWORD,
                null);

        if (loginId != null && loginPassword != null) {
            Intent intent = new Intent(this, LoginActivity.class);
            intent.setAction(CommonValues.ACTION_AUTO_LOGIN);
            intent.putExtra("loginId", loginId);
            intent.putExtra("loginPassword", loginPassword);
            startActivityForResult(intent, CommonConst.REQUEST_CODE_LOGIN);
        } else {
            Intent intent = new Intent(this, LoginActivity.class);
            intent.setAction(CommonValues.ACTION_MANUAL_LOGIN);
            startActivityForResult(intent, CommonConst.REQUEST_CODE_LOGIN);
        }
    }

    private void updateLoginButton() {
        SharedPreferences prefs = getSharedPreferences(
                CommonValues.PREFS_LOGIN, MODE_PRIVATE);
        String loginId = prefs.getString(CommonValues.PREFS_KEY_ID, null);
        String loginPassword = prefs.getString(CommonValues.PREFS_KEY_PASSWORD,
                null);

        if (loginId != null && loginPassword != null) {
            mLoginButton.setText(getString(R.string.administrator));
        } else {
            mLoginButton.setText(getString(R.string.login));
        }
    }

    public void accountSaveToPreferences(String url) {
        // Get id and password from url
        // url: "http://backrib.com/
        //       bbs/login.php?mb_id=***&mb_password=****"
        String[] devide1 = url.split("\\?");
        String[] devide2 = devide1[1].split("\\&");
        String id = devide2[0].substring(6);
        String password = devide2[1].substring(12);

        // Save to preferences
        SharedPreferences prefs = getSharedPreferences(
                CommonValues.PREFS_LOGIN, MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(CommonValues.PREFS_KEY_ID, id);
        editor.putString(CommonValues.PREFS_KEY_PASSWORD, password);
        editor.commit();
    }
    
    public void removeLoginSharedPreference() {
        SharedPreferences prefs = getSharedPreferences(
                CommonValues.PREFS_LOGIN, MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.remove(CommonValues.PREFS_KEY_ID);
        editor.remove(CommonValues.PREFS_KEY_PASSWORD);
        editor.commit();
    }
    
    public boolean checkLoginFromWeb() {
        boolean isLogin = false;
        SharedPreferences prefs = getSharedPreferences(
                CommonValues.PREFS_LOGIN, MODE_PRIVATE);
        String loginId = prefs.getString(CommonValues.PREFS_KEY_ID, null);

        if (loginId != null) {
            isLogin = true;
        } else {
            isLogin = false;
        }

        return isLogin;
    }

}
